﻿///***************************************************************
/// 시  스  템 : Updms.Prj
/// 단위시스템 : PRJ
/// 계      층 : Presentation Layer
/// 프로그램명 : Prj1012m
/// 파  일  명 : Prj1012m.aspx.cs
/// 설      명 : 보고서관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-12-23 송시명   최초 작성
/// CH002  2009-01-14 송시명   검색조건 추가 - 메일전송여부
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.Page;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Prj.Exe;


namespace Updms.Prj
{
	public partial class Prj1012m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Prj1012m";
		public static readonly string gs_path_info = "/updms/Prj/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Prj prj = new CommCode.Prj(LANG_SET);

		//페이징
		private int li_cur_page, li_row_count, li_st_page, li_ed_page;
		protected int li_page_size = 10;// 한 페이지에 출력될 행의수

		//검색
		protected string kw1 = "";	//프로젝트아이디
		protected string kw2 = "";	//구분
		protected string kw3 = "";	//제목
		protected string kw4 = "";	//메일전송여부

		//메뉴 선택값
		protected string gs_sm = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetProjectId();
			SetReportDiv();
			SetSendYn();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		private void SetClientScript()
		{
			//onKeyPress이벤트 (엔터검색)
			txt_search_title.Attributes.Add("onkeypress", "enterSearch(event)");
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			if (Request.QueryString["page"] == null || int.Parse(Request.QueryString["page"]) == 1)
			{
				li_cur_page = 1;
				li_st_page = 0;
				li_ed_page = li_page_size;
			}
			else
			{
				li_cur_page = int.Parse(Request.QueryString["page"]);
				li_st_page = (int.Parse(Request.QueryString["page"]) - 1) * li_page_size;
				li_ed_page = li_st_page + li_page_size;
			}

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_prj_id.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_prj_id.SelectedValue = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = ddl_search_div.SelectedValue;
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						ddl_search_div.SelectedValue = kw2;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))	// url에 값이 없으면
					{
						kw3 = txt_search_title.Text.Trim();
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						txt_search_title.Text = kw3;
					}
					
					if (String.IsNullOrEmpty(Request.QueryString["kw4"]))	// url에 값이 없으면
					{
						kw4 = ddl_search_send_yn.SelectedValue;
					}
					else
					{
						kw4 = Server.UrlDecode(Request.QueryString["kw4"]);
						ddl_search_send_yn.SelectedValue = kw4;
					}
					break;
				case "SEARCH":
					kw1 = ddl_search_prj_id.SelectedValue;
					kw2 = ddl_search_div.SelectedValue;
					kw3 = txt_search_title.Text.Trim();
					kw4 = ddl_search_send_yn.SelectedValue;
					
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw1 = ddl_search_prj_id.SelectedItem.Text;
			string ls_kw2 = ConversionUtil.CompareReplace(ddl_search_div.SelectedItem.Text, DDL_SELECT, "-");

			lbl_search_keyword.Text = ls_kw1 + " / " + ls_kw2 + " / " + kw3 + " / " + kw4;
		}

		#endregion

		#region 마스터 Method (SetProjectId, SetReportDiv, SetSendYn)

		//프로젝트아이디
		private void SetProjectId()
		{
			DataSet lo_ds = new DataSet();
			Prj1010m_NT _Prj1010m_NT = new Prj1010m_NT();

			lo_ds.Merge(_Prj1010m_NT.GetProjectInfoReportY());

			bool lb_is_exist_prj_id = DataSetUtil.CheckRowCount(lo_ds, "UPDMS_PRJ_SUMMARY");

			if (lb_is_exist_prj_id)
			{
				ddl_search_prj_id.Items.Clear();
				ddl_search_prj_id.DataSource = lo_ds;
				ddl_search_prj_id.DataMember = "UPDMS_PRJ_SUMMARY";
				ddl_search_prj_id.DataTextField = "Subject";
				ddl_search_prj_id.DataValueField = "Prj_Id";
				ddl_search_prj_id.DataBind();

				//기본선택 프로젝트 아이디
				string ls_sel_prj_id = DataSetUtil.GetFldStr(lo_ds, "UPDMS_PRJ_SUMMARY", "Sel_Prj_Id");

				for (int i = 0; i < ddl_search_prj_id.Items.Count; i++)
				{
					if (ddl_search_prj_id.Items[i].Value == ls_sel_prj_id)
					{
						ddl_search_prj_id.SelectedValue = ls_sel_prj_id;
					}
				}
			}
			else
			{
				ddl_search_prj_id.Items.Insert(0, new ListItem(DDL_NO_DATA, ""));
				ibtn_search.Attributes.Add("onclick", "msgBox.alert(getMsg(MSG_ERR_140));return false;");
			}
		}

		//보고서구분
		private void SetReportDiv()
		{
			prj.SetReportDiv(ddl_search_div);
			prj.SetReportDiv(ddl_div);

			ddl_search_div.Items.Insert(0, new ListItem(DDL_SELECT, ""));
		}

		//메일전송여부
		private void SetSendYn()
		{
			ddl_search_send_yn.Items.Insert(0, new ListItem(DDL_SELECT, ""));
			ddl_search_send_yn.Items.Insert(1, new ListItem("Y", "Y"));
			ddl_search_send_yn.Items.Insert(2, new ListItem("N", "N"));
		}

		

		#endregion

		#region 디테일 Method (SetStartEndDt, SetReflectDetail)

		//보고시작일,보고종료일 자동계산
		private void SetStartEndDt()
		{
			if (ddl_div.SelectedValue == "AE002")
			{
				//주간인 경우 보고일기준 -7일, -1일
                txt_start_dt.Text = DateUtil.GetCalcDay(txt_report_dt.Text, -7, "yyyy-MM-dd");
                txt_end_dt.Text = DateUtil.GetCalcDay(txt_report_dt.Text, -1, "yyyy-MM-dd");
			}
		}
		
		//디테일반영
		private void SetReflectDetail(int li_row_idx)
		{
			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[li_row_idx].FindControl("lbtn_rc");

			ddl_search_prj_id.SelectedValue = GridView1.DataKeys[li_row_idx].Values["Prj_Id"].ToString();
			ddl_div.SelectedValue			= GridView1.DataKeys[li_row_idx].Values["Div"].ToString();
			txt_report_dt.Text				= GridView1.Rows[li_row_idx].Cells[6].Text;
			txt_start_dt.Text				= GridView1.DataKeys[li_row_idx].Values["Start_Dt"].ToString();
			txt_end_dt.Text					= GridView1.DataKeys[li_row_idx].Values["End_Dt"].ToString();
			txt_title.Text					= lbtn_rc.Text;
			txt_results.Text				= GridView1.DataKeys[li_row_idx].Values["Results"].ToString();
			txt_plans.Text					= GridView1.DataKeys[li_row_idx].Values["Plans"].ToString();

			h_no.Value						= GridView1.Rows[li_row_idx].Cells[1].Text.ToString();				//1.번호
		}

		#endregion

		#region CRUD (SelectProcess, InsertProcess, UpdateProcess, DeleteProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			int li_page_count;

			//검색
			lo_dp.AddProperty("ls_prj_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_div", typeof(string), kw2);
			lo_dp.AddProperty("ls_title", typeof(string), kw3);
			lo_dp.AddProperty("ls_send_yn", typeof(string), kw4);
			
			using (Prj1012m_NT _Prj1012m_NT = new Prj1012m_NT())
			{
				li_row_count = _Prj1012m_NT.GetSearchCount(lo_dp);	// 검색된 행수
				li_page_count = (int)((li_row_count - 1) / li_page_size) + 1;	// 총페이지수 계산

				//모두보기/페이징
				lo_dp.AddProperty("li_st_page", typeof(Int32), (cb_list_all.Checked) ? 0 : li_st_page);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), (cb_list_all.Checked) ? li_row_count : li_ed_page);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
				lbl_page.Visible = !cb_list_all.Checked;

				lo_ds.Merge(_Prj1012m_NT.SelectProcess(lo_dp));
			}

			GridView1.DataSource = lo_ds;
			GridView1.DataBind();

			Pager pager = new Pager(this, ref lbl_page);
			pager.PageNavigation(
				li_cur_page,
				li_page_count,
				gs_path_info + "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&kw2=" + Server.UrlEncode(kw2) + "&kw3=" + Server.UrlEncode(kw3) + "&kw4=" + Server.UrlEncode(kw4) + "&page=");

			//결과출력(키워드, 검색행수)
			ShowKeywordLabel();
			lbl_result_count.Text = li_row_count.ToString("#,###,##0");
		}

		//저장
		private void InsertProcess()
		{
			using (Prj1012m_RT _Prj1012m_RT = new Prj1012m_RT())
			{
				int li_return = _Prj1012m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//수정
		private void UpdateProcess()
		{
			using (Prj1012m_RT _Prj1012m_RT = new Prj1012m_RT())
			{
				int li_return = _Prj1012m_RT.UpdateProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//삭제
		private void DeleteProcess(string ls_xml)
		{
			using (Prj1012m_RT _Prj1012m_RT = new Prj1012m_RT())
			{
				int li_return = _Prj1012m_RT.DeleteProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_004" : "MSG_ERR_103";	//삭제되었습니다:삭제할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);
				
				SearchProcess();
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			ClearValue();
			SelectProcess();
		}

		#endregion

		#region SetValue, ClearValue

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();
			
			lo_dp.AddProperty("Seq", typeof(string), lbl_pk.Text);
			lo_dp.AddProperty("Prj_Id", typeof(string), ddl_search_prj_id.SelectedValue);
			lo_dp.AddProperty("Div", typeof(string), ddl_div.SelectedValue);
			lo_dp.AddProperty("Report_Dt", typeof(string), ConversionUtil.DefaultValue(txt_report_dt.Text));
			lo_dp.AddProperty("Start_Dt", typeof(string), ConversionUtil.DefaultValue(txt_start_dt.Text));
			lo_dp.AddProperty("End_Dt", typeof(string), ConversionUtil.DefaultValue(txt_end_dt.Text));
			lo_dp.AddProperty("Title", typeof(string), ConversionUtil.DefaultValue(txt_title.Text));
			lo_dp.AddProperty("Results", typeof(string), ConversionUtil.DefaultValue(txt_results.Text));
			lo_dp.AddProperty("Plans", typeof(string), ConversionUtil.DefaultValue(txt_plans.Text));
			lo_dp.AddProperty("Create_User", typeof(string), USER_ID);
			lo_dp.AddProperty("Create_Dt", typeof(string), "");
			lo_dp.AddProperty("Update_User", typeof(string), USER_ID);
			lo_dp.AddProperty("Update_Dt", typeof(string), "");

			return lo_dp;
		}

		//ClearValue
		private void ClearValue()
		{
			lbl_pk.Text = "";
			h_no.Value = "";
			ddl_div.SelectedIndex = 0;
			ce_report_dt.SelectedDate = DateTime.Now.AddDays(0);
			ce_start_dt.SelectedDate = DateTime.Now.AddDays(0);
			ce_end_dt.SelectedDate = DateTime.Now.AddDays(0);
			txt_title.Text = "";
			txt_results.Text = "";
			txt_plans.Text = "";
		}

		#endregion

		#region Page_PreRender

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			//페이지모드 처리
			string ls_class = String.IsNullOrEmpty(lbl_pk.Text) ? "sbtn sbtn_mode_i" : "sbtn sbtn_mode_u";
			string ls_title = String.IsNullOrEmpty(lbl_pk.Text) ? "입력" : "수정";
			btn_chg_mode.Attributes.Add("class", ls_class);
			btn_chg_mode.Attributes.Add("title", ls_title);

			ChangePageMode();
		}

		//ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}
				
		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text
					= cb_list_all.Checked
					? (li_row_count - e.Row.RowIndex).ToString()
					: ((li_row_count - ((li_cur_page - 1) * li_page_size)) - e.Row.RowIndex).ToString();

				//전송여부
				e.Row.Cells[14].Attributes.Add("class", (e.Row.Cells[14].Text == "N") ? "color_darkred" : "color_gray");
			}

			//머지
			//SMGridView sGv = new SMGridView(this.Page, ref GridView1);
			//sGv.RowSpanGridView(GridView1, 머지할 index번호);
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			GridView gv = (GridView)sender;
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[row.RowIndex].FindControl("lbtn_rc");

			//0.체크박스
			h_no.Value						= row.Cells[1].Text.ToString();								//1.번호
			lbl_pk.Text						= gv.DataKeys[row.RowIndex].Values["Seq"].ToString();		//2.Seq
			ddl_search_prj_id.SelectedValue = gv.DataKeys[row.RowIndex].Values["Prj_Id"].ToString();	//3.Prj_Id
			ddl_div.SelectedValue			= gv.DataKeys[row.RowIndex].Values["Div"].ToString();		//4.Div
																										//5.Div_Nm
			txt_report_dt.Text				= row.Cells[6].Text.ToString();								//6.Report_Dt
			txt_start_dt.Text				= gv.DataKeys[row.RowIndex].Values["Start_Dt"].ToString();	//7.Start_Dt
			txt_end_dt.Text					= gv.DataKeys[row.RowIndex].Values["End_Dt"].ToString();	//8.End_Dt
			txt_title.Text					= lbtn_rc.Text;												//9.Title(template)
			txt_results.Text				= gv.DataKeys[row.RowIndex].Values["Results"].ToString();	//10.Results
			txt_plans.Text					= gv.DataKeys[row.RowIndex].Values["Plans"].ToString();		//11.Plans
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			if (global.CheckSaveMode("UPDMS_PRJ_REPORT_MGT", "Seq", lbl_pk.Text.Trim()))
			{
				UpdateProcess();
			}
			else
			{
				InsertProcess();
			}
		}

		//삭제
		protected void ibtn_delete_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();
					
					sb.Append("<UPDMS_PRJ_REPORT_MGT>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("</UPDMS_PRJ_REPORT_MGT>");
				}
			}
			sb.Append("</UPDMS>");

			DeleteProcess(sb.ToString());
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_prj_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_div", typeof(string), kw2);
			lo_dp.AddProperty("ls_title", typeof(string), kw3);
			lo_dp.AddProperty("ls_send_yn", typeof(string), kw4);
			
			using (Prj1012m_NT _Prj1012m_NT = new Prj1012m_NT())
			{
				li_row_count = _Prj1012m_NT.GetSearchCount(lo_dp);

				lo_dp.AddProperty("li_st_page", typeof(Int32), 0);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), li_row_count);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

				lo_ds.Merge(_Prj1012m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//보고일 자동계산
		protected void lbtn_create_dt_Click(object sender, EventArgs e)
		{
			SetStartEndDt();
		}	
		
		//디테일 초기화
		protected void lbtn_init_detail_Click(object sender, EventArgs e)
		{
			ClearValue();
		}

		//모드변경 I -> U
		protected void lbtn_chg_mode_Click(object sender, EventArgs e)
		{
			h_no.Value = "";
			lbl_pk.Text = "";
		}

		#endregion

		
		
	}
}
